<template>
  <k-view
    :class="['table', hasAuth ? '' : 'not-auth']"
    v-click-outside="clickOutSide"
    @click.stop="clickOutSide"
  >
    <template>
      <k-view class="header">
        <k-view v-if="isPremium" class="header-item column-1 premium" @click="showVisibel"
          >{{ selectArr[selectIndex] }}<k-image class="more" :src="changeImgSrc"></k-image
        ></k-view>
        <k-view v-else class="header-item column-1">指标</k-view>
        <k-view class="header-item column-2"></k-view>
        <k-view class="header-item column-3 jcc">{{ stock1.stockName || '--' }}</k-view>
        <k-view class="header-item column-4">{{ stock2.stockName || '--' }}</k-view>
      </k-view>
      <template v-if="basicTableData && basicTableData.length">
        <k-view class="body" v-for="(item, index) in basicTableData" :key="item.name">
          <k-view :class="['body-header', item.isShow ? '' : 'closed']" @click="clickHeader(index)">
            <k-view class="column-1"
              >{{ item.name || '--'
              }}<k-image :class="['arrow', item.isShow ? '' : 'arrow-down']" :src="foldIcon"
            /></k-view>
            <k-view class="column-2"></k-view>
            <!-- 4表示取右侧股票全风险项 -->
            <k-view class="column-3 jcc"
              ><template
                v-if="
                  getStock1Value(item.name, '', 'risk_num') &&
                  getStock1Value(item.name, '', 'risk_num') !== '/' &&
                  selectIndex !== 3
                "
                ><k-text class="risk-num">{{ getStock1Value(item.name, '', 'risk_num') }}</k-text
                >项风险</template
              ></k-view
            >
            <!-- 3表示取左侧股票全风险项 -->
            <k-view class="column-4"
              ><template
                v-if="
                  getStock2Value(item.name, '', 'risk_num') &&
                  getStock2Value(item.name, '', 'risk_num') !== '/' &&
                  selectIndex !== 2
                "
                ><k-text class="risk-num">{{ getStock2Value(item.name, '', 'risk_num') }}</k-text
                >项风险</template
              ></k-view
            >
          </k-view>
          <k-view class="body-main" v-show="item.isShow">
            <k-view
              class="body-main-item"
              v-for="(index3ListItem, i) in item.index3_list"
              :key="index3ListItem.name"
            >
              <k-view class="column-1"
                >{{ index3ListItem.name || '--'
                }}<k-image
                  class="abnormal-icon"
                  :src="theme === 'dark' ? questionIconDark : questionIcon"
                  @click.stop="handleDialog(item.name, index3ListItem.name)"
                  v-if="
                    getStock1Value(item.name, index3ListItem.name, 'risk') ||
                    getStock2Value(item.name, index3ListItem.name, 'risk')
                  "
              /></k-view>
              <k-view class="column-2">
                <k-view class="line">评分</k-view>
                <k-view class="line">排名</k-view>
                <k-view class="line">指标值</k-view>
              </k-view>
              <k-view
                :class="[
                  'column-3',
                  getStock1Value(item.name, index3ListItem.name, 'risk') ? 'abnormal' : '',
                ]"
                @click.stop="clickRow(!!auth.stock1, stock1.stockName)"
              >
                <k-view class="line">{{
                  getStock1Value(item.name, index3ListItem.name, 'score')
                }}</k-view>
                <k-view class="line">{{
                  getStock1Value(item.name, index3ListItem.name, 'rank')
                }}</k-view>
                <k-view class="line">
                  <Notice
                    :content="getStock1Value(item.name, index3ListItem.name, 'value') + ''"
                    @clickPopup="clickPopup(index, i, 3)"
                  /><ScoreReadPoup
                    v-if="
                      index === showIndexArr[0] && i === showIndexArr[1] && showIndexArr[2] === 3
                    "
                    title=""
                    :content="getStock1Value(item.name, index3ListItem.name, 'value')"
                    linkText=""
                    bottom="25px"
                    left="-60px"
                    width="200px"
                  />
                </k-view>
              </k-view>
              <k-view
                :class="[
                  'column-4',
                  getStock2Value(item.name, index3ListItem.name, 'risk') ? 'abnormal' : '',
                ]"
                @click.stop="clickRow(!!auth.stock2, stock2.stockName)"
              >
                <k-view class="line">{{
                  getStock2Value(item.name, index3ListItem.name, 'score')
                }}</k-view>
                <k-view class="line"
                  >{{ getStock2Value(item.name, index3ListItem.name, 'rank') }}
                </k-view>
                <k-view class="line">
                  <Notice
                    :content="getStock2Value(item.name, index3ListItem.name, 'value') + ''"
                    @clickPopup="clickPopup(index, i, 4)"
                  /><ScoreReadPoup
                    v-if="
                      index === showIndexArr[0] && i === showIndexArr[1] && showIndexArr[2] === 4
                    "
                    title=""
                    :content="getStock2Value(item.name, index3ListItem.name, 'value')"
                    linkText=""
                    bottom="25px"
                    left="-60px"
                    width="200px"
                  />
                </k-view>
              </k-view>
            </k-view>
          </k-view>
        </k-view>
      </template>
      <RiskEmpty v-else :text="`${activeName}中无可PK的风险指标`" />
      <!-- hasClickBuy作用是激活onshow事件，防止购买完成之后回到页面不刷新 -->
      <SellMask
        v-if="basicTableData && basicTableData.length && !hasAuth"
        @hasClickBuy="emits('hasClickBuy')"
        @clickBuy="clickBuy(stock1.stockName, stock2.stockName)"
        :pageid="PAGEID.PK"
      />
      <confirm-dialog
        v-if="showDialog"
        title="对比详情"
        :subTitle="contentOptions.subTitle || '--'"
        confirm-text="知道了"
        hide-cancel
        @success="showDialog = false"
        @fail="showDialog = false"
      >
        <k-view class="content">
          <k-view
            class="desc"
            v-if="
              contentOptions.stock1 &&
              !['――', 'null', '--'].includes(contentOptions.stock1) &&
              contentOptions.stock1isRisk
            "
          >
            <k-text class="title title1">{{ stock1.stockName }}</k-text>
            <k-text>{{ contentOptions.stock1 }}</k-text>
          </k-view>
          <k-view
            class="desc"
            v-if="
              contentOptions.stock2 &&
              !['――', 'null', '--'].includes(contentOptions.stock2) &&
              contentOptions.stock2isRisk
            "
          >
            <k-text class="title title2">{{ stock2.stockName }}</k-text>
            <k-text>{{ contentOptions.stock2 }}</k-text>
          </k-view>
        </k-view>
      </confirm-dialog>
      <PickerWheel
        :visible="visible"
        :menu="selectArr"
        :selectIndex="selectIndex"
        @confirm="confirm"
        @cancel="visible = false"
      />
      <Dialog
        :isShow="dialogIsShow"
        title="解锁股票"
        :subTitle="`你确定解锁${subTitleFragment}么`"
        @confirm="gotoBuy(auth.stock1, auth.stock2, stock1, stock2)"
        @cancel="dialogIsShow = false"
      />
    </template>
  </k-view>
</template>

<script setup lang="ts">
import { watch, ref, reactive, computed, nextTick } from 'vue';

import ConfirmDialog from '@/components/Intro/ConfirmDialog.vue';
import SellMask from '@/components/StockDiagnosis/sellMask.vue';
import RiskEmpty from '@/components/StockDiagnosis/riskEmpty.vue';
import PickerWheel from '@/components/Pk/PickerWheel.vue';
import ScoreReadPoup from '@/components/StockDiagnosis/scoreReadPoup.vue';
import Notice from '@/components/StockDiagnosis/Notice.vue';
import Dialog from '@/components/common/Dialog.vue';

import foldIcon from '../../assets/index/fold-icon.png';
import questionIcon from '@/assets/index/question_icon.png';
import questionIconDark from '@/assets/index/question_icon_dark.png';

import { PAGEID } from '@/config/stat';
import getThemeHooks from '@/hooks/getThemeHooks';
import { Auth } from '@/types/pk.d';
import { sendClickStat } from '@/utils/stat';
import { transferToNumber } from '@/utils';
import vClickOutside from 'vue-click-outside';
import { TableData, Index3List } from '@/types/table';
import { StockInfoItem } from '@/types/pk.d';
import useDialog from '@/hooks/pk/useDialog';

interface Props {
  stock1: StockInfoItem;
  stock2: StockInfoItem;
  tableData: {
    tableData1: TableData[];
    tableData2: TableData[];
  };
  auth: { stock1: Auth; stock2: Auth };
  activeName: string;
}
const props = defineProps<Props>();
interface Emits {
  (e: 'hasClickBuy'): void;
}
const emits = defineEmits<Emits>();
const { theme, getTheme } = getThemeHooks();
getTheme();
const changeImgSrc = computed<string>(() =>
  theme.value === 'dark'
    ? '//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/53074ed4-5f85-4ec1-a4cf-c96763fa31c4.png'
    : '//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/918099ea-c6f6-4ec7-88c8-06853e696f34.png'
);
const isPremium = computed(() =>
  [props.auth.stock1, props.auth.stock2].every(item => item === Auth.premium)
);
const hasAuth = computed(() => !!Object.values(props.auth).find(item => item !== Auth.free));
// 为原先的tableData中添加展开收起,并且过滤stock1中的风险数据
const getNewTableData = (tableData: TableData[], hasFilter: boolean = true) => {
  const result: TableData[] = JSON.parse(JSON.stringify(tableData));
  result.forEach(item => {
    item.isShow = true;
    hasFilter && (item.index3_list = item.index3_list.filter(i => i.risk));
  });
  return result.filter(item => item.index3_list.length);
};
// 合并两个股票的指标
const mergeStocks = <T>(stock1: T[], stock2: T[], isFirst: boolean = false): T[] => {
  const result: TableData[] = JSON.parse(JSON.stringify(stock1));
  stock2.forEach(item => {
    const findResultIndex = result.findIndex(i => i.name === item.name);
    if (findResultIndex === -1) {
      result.push(item);
    } else if (isFirst) {
      // 在二级指标,需要递归使用一次函数
      result[findResultIndex].index3_list = mergeStocks(
        result[findResultIndex].index3_list,
        item.index3_list
      );
    } else if (!isFirst && item.risk) {
      // 在3级指标,且是风险指标
      result[findResultIndex].risk = item.risk;
    }
  });
  return result as T[];
};
const tableData1 = ref<TableData[]>([]);
const tableData2 = ref<TableData[]>([]);
const basicTableData = ref<TableData[]>([]);
// 格式化指标值
const formatData = <T>(num: T): T => {
  if (num && num === '1.0') {
    return '是' as T;
  } else if (num && num === '0.0') {
    return '否' as T;
  } else if (num + '' === 'null') {
    return '/' as T;
  } else if (num) {
    const numFloat = parseFloat(num + '');
    const numFloatFixed = numFloat.toFixed(2);
    if (!parseFloat(numFloatFixed)) {
      return transferToNumber(numFloat) as T;
    }
    const suffix = (num + '').includes('%') ? '%' : '';
    return (numFloatFixed + suffix) as T;
  } else {
    return num;
  }
};
// 获取pk第一支股票信息
const getStock1Value = (
  index2Name: string,
  index3Name: string,
  param: keyof Index3List | 'risk_num'
) => {
  return getStockValue(index2Name, index3Name, param, 1);
};
// 获取pk第二支股票信息
const getStock2Value = (
  index2Name: string,
  index3Name: string,
  param: keyof Index3List | 'risk_num'
) => {
  return getStockValue(index2Name, index3Name, param, 2);
};
// 获取股票信息
const getStockValue = (
  index2Name: string,
  index3Name: string,
  param: keyof Index3List | 'risk_num',
  stockNum: 1 | 2
) => {
  if (isOnlyBuyOne.value && !props.auth[`stock${stockNum}`]) {
    return '**';
  }
  const isRisk = param === 'risk';
  const tableData = stockNum === 1 ? tableData1 : tableData2;
  const index2ListItem = tableData.value.find(item => item.name === index2Name);
  if (!index2ListItem) {
    return isRisk ? false : '/';
  }
  if (index3Name === '' && param === 'risk_num') {
    return index2ListItem.risk_num;
  }
  const index3ListItem = index2ListItem.index3_list.find(item => item.name === index3Name);
  if (!index3ListItem) {
    return isRisk ? false : '/';
  }
  if (['score', 'rank'].includes(param)) {
    return index3ListItem[param as keyof Index3List] + '' === 'null'
      ? '/'
      : index3ListItem[param as keyof Index3List];
  } else if (param === 'value') {
    return formatData(index3ListItem[param] + '');
  } else {
    return index3ListItem[param as keyof Index3List];
  }
};
// 展开收起
const clickHeader = (index: number) => {
  basicTableData.value[index].isShow = !basicTableData.value[index].isShow;
};
// 是否展示弹框
const showDialog = ref<boolean>(false);
// 弹框中的内容
const contentOptions = reactive({
  subTitle: '',
  stock1: '',
  stock2: '',
  stock1isRisk: false,
  stock2isRisk: false,
});
// 打开弹框
const handleDialog = (index2Name: string, index3Name: string) => {
  const index2ListItemStock1 = tableData1.value.find(item => item.name === index2Name);
  const index2ListItemStock2 = tableData2.value.find(item => item.name === index2Name);
  const index3ListItemStock1 = index2ListItemStock1?.index3_list.find(
    item => item.name === index3Name
  );
  const index3ListItemStock2 = index2ListItemStock2?.index3_list.find(
    item => item.name === index3Name
  );
  contentOptions.subTitle = index3ListItemStock1?.name || index3ListItemStock2?.name || '--';
  contentOptions.stock1 = index3ListItemStock1?.words || '--';
  contentOptions.stock2 = index3ListItemStock2?.words || '--';
  contentOptions.stock1isRisk = !!index3ListItemStock1?.risk;
  contentOptions.stock2isRisk = !!index3ListItemStock2?.risk;
  showDialog.value = true;
};

// 切换指标
const visible = ref<boolean>(false);
const selectArr = computed<string[]>(() => [
  '全部指标',
  '全部风险指标',
  `${props.stock1.stockName || '--'}风险项`,
  `${props.stock2.stockName || '--'}风险项`,
]);
const showVisibel = () => {
  sendClickStat(`${PAGEID.PK}.filter.click`);
  visible.value = true;
};
// 默认选中左侧全风险项
const selectIndex = ref<number>(2);
const confirm = (selectedIndex: number) => {
  selectIndex.value = selectedIndex;
  visible.value = false;
};

const showIndexArr = ref<[number, number, number]>([-1, -1, -1]);
const clickPopup = (index: number, i: number, column: 3 | 4) => {
  nextTick(() => {
    showIndexArr.value = [index, i, column];
  });
};
const clickOutSide = () => {
  showIndexArr.value = [-1, -1, -1];
};

watch([() => props.tableData, selectIndex], () => {
  tableData1.value = props.tableData.tableData1;
  tableData2.value = props.tableData.tableData2;
  const actions: { [key: number | string]: Function } = {
    0: () => getNewTableData(mergeStocks(tableData1.value, tableData2.value, true), false),
    1: () => getNewTableData(mergeStocks(tableData1.value, tableData2.value, true), true),
    2: () => getNewTableData(tableData1.value),
    3: () => getNewTableData(tableData2.value),
    default: () => getNewTableData(tableData1.value),
  };
  const selectedAction = actions[selectIndex.value] || actions.default;
  basicTableData.value = selectedAction();
});

const isOnlyBuyOne = ref<boolean>(false);
watch(
  () => props.auth,
  () => {
    const filteredAuth = Object.values(props.auth).filter(item => item === Auth.free);
    isOnlyBuyOne.value = filteredAuth.length === 1;
    if (props.auth.stock1 === Auth.free && props.auth.stock2 !== Auth.free) {
      selectIndex.value = 3;
    }
  },
  {
    deep: true,
  }
);

const {
  // 购买dialog是否显示
  dialogIsShow,
  // 副标题片段
  subTitleFragment,
  // 点击获取权限
  clickBuy,
  // 点击列
  clickRow,
  // 确认购买
  gotoBuy,
} = useDialog(hasAuth, isOnlyBuyOne);
</script>

<style scoped lang="less">
.table {
  background-color: #ffffff;

  .header {
    display: flex;
    padding: 16px 20px;
    font-size: 26px;

    .header-item:nth-of-type(1) {
      font-family: PingFangSC-Regular;
      color: rgba(0, 0, 0, 0.4);
      letter-spacing: 0;
      line-height: 40px;
      font-weight: 400;

      &.premium {
        font-family: PingFangSC-Regular;
        font-size: 26px;
        color: rgba(0, 0, 0, 0.84);
        letter-spacing: 0;
        font-weight: 400;

        .more {
          width: 10px;
          height: 10px;
          margin-left: 8px;
        }
      }
    }

    .header-item:nth-of-type(3) {
      font-family: PingFangSC-Medium;
      color: #ff2436 !important;
      font-weight: bold;
    }

    .header-item:nth-of-type(4) {
      font-family: PingFangSC-Medium;
      color: #3366ff !important;
      font-weight: bold;
    }
  }

  .body {
    &-header {
      height: 56px;
      display: flex;
      align-items: center;
      font-family: PingFangSC-Regular;
      font-size: 26px;
      padding: 0 20px;
      background-color: #f5f5f5;
      color: #262626;
      letter-spacing: 0;
      line-height: 40px;
      font-weight: 400;

      .arrow {
        width: 16px;
        height: 12px;
        margin-left: 16px;
      }

      .arrow-down {
        transform: rotate(180deg);
      }

      .risk-num {
        color: #ff2436;
        display: inline;
      }
    }

    .closed {
      margin-bottom: 4px;
    }

    &-main {
      &-item {
        display: flex;
        padding-left: 20px;
        font-family: PingFangSC-Regular;
        font-size: 26px;
        color: rgba(0, 0, 0, 0.84);
        letter-spacing: 0;
        line-height: 60px;
        font-weight: 400;

        .column-1 {
          display: flex;
          align-items: center;
          height: 196px;
          line-height: 40px;
          border-bottom: 1px solid #edeff2;
          border-right: 1px solid #edeff2;
          padding-right: 10px;

          .abnormal-icon {
            width: 26px;
            height: 26px;
            margin-left: 8px;
          }
        }

        .column-2 {
          color: rgba(0, 0, 0, 0.4);

          .line {
            padding-left: 16px;
          }
        }

        .line {
          height: 65px;
          border-bottom: 1px solid #edeff2;
        }

        .abnormal .line {
          color: rgb(255, 36, 54);
          background-color: rgba(255, 36, 54, 0.05);
        }
      }
    }
  }

  .column-1 {
    width: 236px;
    text-align: left;
  }

  .column-2 {
    width: 164px;
    text-align: left;
  }

  .column-3 {
    width: 172px;
    text-align: right;
    &.jcc {
      display: flex;
      justify-content: center;
    }
    .line {
      padding-right: 40px;
      width: 162px;
      &:last-child {
        position: relative;
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  .column-4 {
    width: 172px;
    text-align: right;
    .line {
      padding-right: 20px;
      width: 162px;
      &:last-child {
        position: relative;
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  .content {
    font-family: PingFangSC-Regular;
    font-size: 28px;
    color: #595959;
    line-height: 40px;
    font-weight: 400;

    .desc {
      padding-top: 32px;
    }

    .title {
      display: inline;
      position: relative;
      font-family: PingFangSC-Medium;
      font-size: 28px;
      line-height: 36px;
      font-weight: bold;
    }

    .title1 {
      color: #ff2436;

      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 8px;
        left: 0;
        bottom: 2px;
        background-color: rgba(255, 36, 54, 0.2);
        border-radius: 4px;
      }
    }

    .title2 {
      color: #3366ff;
      margin-top: 40px;

      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 8px;
        left: 0;
        bottom: 2px;
        background-color: rgba(51, 102, 255, 0.2);
        border-radius: 4px;
      }
    }
  }
}

.not-auth {
  overflow: hidden;
  height: 872px;

  :deep(.mask) {
    height: 820px;
    bottom: 0;
    left: 0;
    padding-bottom: 94px;
  }
}

[theme-mode='black'] .table {
  background-color: #1c1c1c;

  .body-header {
    background-color: #212121;
  }

  .column-1,
  .column-3,
  .column-4 {
    color: rgba(255, 255, 255, 0.84) !important;
  }

  .body-main {
    &-item {
      .column-1 {
        border-bottom: 1px solid rgba(255, 255, 255, 0.06);
        border-right: 1px solid rgba(255, 255, 255, 0.06);
      }

      .line {
        border-bottom: 1px solid rgba(255, 255, 255, 0.06);
      }
    }
  }

  .column-2 {
    color: rgba(255, 255, 255, 0.4);
  }

  .content {
    :deep(.kfv-text:not(.title)) {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
</style>
